<?php
class Default_Model_Country
{
    private $_table;
	public function __construct(){
		$this->_table = new Default_Model_DbTable_Country();
	}


	public function add($row){
		return $this->_table->insert($row);
	}

	public  function update($row,$value,$field='country_id'){
		$where = $this->_table->getAdapter()->quoteInto("{$field} = ?",$value);
		return $this->_table->update($row, $where);

	}


	public function delete($value,$field='country_id'){

		$where = $this->_table->getAdapter()->quoteInto("{$field} = ?", $value);

		return $this->_table->delete($where);

	}


	public function getByValue($value,$field='country_id'){
        $select = $this->_table->getAdapter()->select();
        $table  = $this->_table->info('name');
        $select->from($table,'*');
        $select->where("{$field} = ?",$value);
		return $this->_table->getAdapter()->fetchRow($select);
	}
	public function getIdByName($country) {
	    $db = $this->_table->getAdapter(); 
		$country = trim($country);
		$sql = "select country_id from country where en_name='$country' or cn_name = '$country' or country_code='$country' limit 1";
		$id =  $db->fetchOne($sql);
		if ($id){
			return $id;
		}
		$sql = "select country_id from country where concat(';',country_alias,';')   like '%;$country;%' limit 1";
		$id =  $db->fetchOne($sql);
		if ($id){
			return $id;
		}
 		return false;
	}

    public function getByCondition($condition,$type='*',$orderby="sort DESC",$page=0,$pageSize=0){
        $select = $this->_table->getAdapter()->select();
        $table  = $this->_table->info('name');
        $select->from($table,$type);
        $select->where("1 =?",1);
        if(isset($condition["cn_name"]) && $condition["cn_name"]!=''){
            $select->where(" cn_name =?",$condition["cn_name"]);
        }
		if(isset($condition["en_name"]) && $condition["en_name"]!=''){
            $select->where(" en_name = ?",$condition["en_name"]);
        }
        if(isset($condition["country_id"]) && $condition["country_id"]!=''){
            $select->where(" country_id <>?",$condition["country_id"]);
        }

        if('count(*)'==$type){
            return $this->_table->getAdapter()->fetchone($select);
        }else{
            if($orderby!='')
            {
                $orderbyArr= explode(',',$orderby);
                foreach($orderbyArr as $order)
                {
                    $select->order($order);
                }

            }else{
				 $select->order("sort DESC");
			}
            if($pageSize>0 && $page>0)
            {

                $start = ($page-1)*$pageSize;
                $select->limit($pageSize,$start);
            }
		
		    return $this->_table->getAdapter()->fetchAll($select);
        }
	}
}